package com.gump.essay.demo.wapper;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;

/**
 * 在使用HTTP协议实现应用间接口通信时，服务端读取客户端请求过来的数据，会用到request.getInputStream()，
 * 第一次读取的时候可以读取到数据，但是接下来的读取操作都读取不到数据
 */
public class RequestBodyRequestWrapper extends HttpServletRequestWrapper {

	private final String decryptRequestBody;

	public RequestBodyRequestWrapper(HttpServletRequest request, String decryptRequestBody) throws IOException {
		super(request);
		this.decryptRequestBody = decryptRequestBody;
	}

	public String getRequestBody() {
		return decryptRequestBody;
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new StringReader(decryptRequestBody));
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream bais = new ByteArrayInputStream(decryptRequestBody.getBytes("UTF-8"));

		return new ServletInputStream() {

			@Override
			public int read() throws IOException {
				return bais.read();
			}

			@Override
			public boolean isFinished() {
				return false;
			}

			@Override
			public boolean isReady() {
				return false;
			}

			@Override
			public void setReadListener(ReadListener readListener) {
			}
		};
	}
}
